import math


def f(x):
    '''
    定义f(x)
    :param x: 需要计算的函数值
    :return: 返回sinx/x 的值
    '''
    return math.exp(-x)


def simpr(f, a, b, n):
    """simpr函数为用复合辛普森公式求积分
       f是被积函数
       a,b分别为积分的上下限
       n是子区间的个数
       s是梯形总面积，即所求积分数值"""
    h = (b - a) / (2 * n)
    s1 = 0
    s2 = 0
    for k in range(1, n + 1):
        x = a + h * (2 * k - 1)
        s1 = s1 + f(x)
    for k in range(1, n):
        x = a + h * 2 * k
        s2 = s2 + f(x)
    s = h * (f(a) + f(b) + 4 * s1 + 2 * s2) / 3
    err = -math.pow((b - a), 5) / (90 * 32) * f(0)
    return s, err


if __name__ == '__main__':
    # 积分下限
    a = 0
    # 积分上限
    b = 1
    n = 1000
    sum, err = simpr(f, a, b, n)
    print("结果为---", sum, "误差为---", err)
